/**
 * 
 */
package com.ywyself.ext.render;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.Cookie;

import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.render.Render;
import com.ywyself.ext.utils.YsVerifyUtils;

/**
 * 验证码放置在了redis中
 * 
 * @author ywyself
 * @createdate 2017年9月8日下午5:16:49
 */
public class YsCaptchaRender extends Render {
	protected int seconds = 2 * 60;

	/**
	 * 过期时间 3*60s
	 */
	public YsCaptchaRender() {
		this.seconds = 2 * 60;
	}

	/**
	 * 过期时间
	 * 
	 * @param seconds
	 *            单位为秒
	 */
	public YsCaptchaRender(int seconds) {
		this.seconds = seconds;
	}

	/**
	 * 验证码是否正确
	 * 
	 * @param code
	 *            验证码
	 * @return true|正确
	 */
	public static boolean validate(Controller controller, String code) {
		// 从cookie中取出验证码
		String captchaKey = controller.getCookie("_YsCaptcha_code");
		if (StrKit.isBlank(captchaKey)) {
			return false;
		}
		if (!captchaKey.equals(encryipt(code.toLowerCase()))) {
			return false;
		}
		Cache sessionCache = Redis.use();
		String code2 = sessionCache.get(encryipt(code.toLowerCase()) + "");
		if (!StrKit.isBlank(code2)) {
			sessionCache.del(encryipt(code.toLowerCase()));
			return true;
		}
		return false;
	}

	private static String encryipt(String code) {
		return HashKit.md5(HashKit.md5(code));
	}

	@Override
	public void render() {
		String code = YsVerifyUtils.getCaptchaCode();
		Cache sessionCache = Redis.use();
		sessionCache.setex(encryipt(code.toLowerCase()), seconds, code);
		// 对放置在cookie中的验证码值进行加密存放
		Cookie cookie = new Cookie("_YsCaptcha_code", encryipt(code.toLowerCase()));
		cookie.setMaxAge(-1);
		cookie.setPath("/");
		response.addCookie(cookie);
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		OutputStream outputStream = null;
		try {
			outputStream = response.getOutputStream();
			YsVerifyUtils.getCaptchaStream(code, 38, outputStream);
			outputStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
